import React from "react";
import { useNavigate } from "react-router-dom";
import api from "src/http/api";
import { EntityProps } from "src/utils/interface";

import {
  Table,
  Space,
  Button,
  Popconfirm,
  notification,
  TableProps,
} from "antd";
import { EditOutlined, ReadOutlined, DeleteOutlined } from "@ant-design/icons";
import SearchForm from "src/components/SearchForm";
import EntityInfoDrawer from "src/components/EntityInfoDrawer";
import SelectStorageFormButton from "./schema";

import globalStyles from "src/public/css/index.scss";
import styles from "./index.scss";

const { useEffect, useState, useRef } = React;

const Entity: React.FC = () => {
  const [curEntityName, setCurEntityName] = useState("");

  // --------------------- detail详情部分的变量与逻辑：开始 -----------------------
  const [detailVisible, setDetailVisible] = useState(false);

  const onDetailClose = () => setDetailVisible(false);

  const onDetailOpen = (EntityName: string) => {
    setCurEntityName(EntityName);
    setDetailVisible(true);
  };
  // --------------------- detail详情部分的变量与逻辑：结束 -----------------------

  // --------------------- 表格部分的变量与逻辑：开始 -----------------------
  const [tableData, setTableData] = useState([] as EntityProps[]);
  const tableDataFlag = useRef(false); // 当返回的表格数据为空时，停止 loading 状态
  const navigate = useNavigate();

  // 处理 查找 请求
  const handleAutoSubmit = (formData: any) => {
    api.getEntity(formData).then((res: any) => {
      setTableData(res.data);
    });
  };

  const deleteEntity = (record: EntityProps) => {
    api.deleteEntity({ entityName: record.entityName }).then(async () => {
      await api.getEntity().then((res: any) => {
        setTableData(res.data);
      });
      notification.success({
        message: "Success",
        description: "删除 entity 成功",
      });
    });
  };

  const tableProps: TableProps<EntityProps> = {
    bordered: true,
    rowKey: "entityName",
    loading: tableData.length === 0 && !tableDataFlag.current,
    dataSource: tableData,
    className: (globalStyles as any).tableTdPadding,
    columns: [
      {
        title: "Name",
        dataIndex: "entityName",
        width: 250,
      },
      {
        title: "Owners",
        dataIndex: "owners",
        width: 150,
        render: (value, record) => (
          <div style={{ color: "#1890ff", cursor: "pointer" }}>
            {value.join(" ")}
          </div>
        ),
      },
      {
        title: "Description",
        dataIndex: "description",
      },
      {
        title: "Operations",
        width: 300,
        render: (value, record) => (
          <Space>
            <Button
              type="primary"
              icon={<EditOutlined />}
              onClick={() => {
                navigate(
                  `/entity/form?operate=edit&entityName=${record.entityName}`
                );
              }}
            >
              编辑
            </Button>
            <Button
              icon={<ReadOutlined />}
              onClick={() => onDetailOpen(record.entityName)}
            >
              详情
            </Button>
            <Popconfirm
              title="确定要删除吗？"
              okText="确定"
              cancelText="取消"
              onConfirm={() => deleteEntity(record)}
            >
              <Button danger icon={<DeleteOutlined />}>
                Delete
              </Button>
            </Popconfirm>
          </Space>
        ),
      },
    ],
  };

  useEffect(() => {
    api.getEntity().then((res: any) => {
      if (res.data.length === 0) {
        tableDataFlag.current = false;
      } else {
        tableDataFlag.current = true;
      }
      setTableData(res.data);
    });
  }, []);
  // --------------------- 表格部分的变量与逻辑：结束 -----------------------

  return (
    <div className={(styles as any).content}>
      <div className={(styles as any).query}>
        <SearchForm type="entity" onAutoSubmit={handleAutoSubmit} />
        <SelectStorageFormButton />
      </div>

      <Table {...tableProps} />

      <EntityInfoDrawer
        entityName={curEntityName}
        visible={detailVisible}
        onClose={onDetailClose}
      />
    </div>
  );
};

export default Entity;
